package io.renren.controller;


import io.renren.annotation.Login;
import io.renren.annotation.SysLog;
import io.renren.common.utils.R;
import io.renren.common.validator.ValidatorUtils;
import io.renren.entity.UserEntity;
import io.renren.form.LoginForm;
import io.renren.service.TokenService;
import io.renren.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.util.Map;

/**
 * 登录接口
 *
 * @author chenshun
 * @email sunlightcs@gmail.com
 * @date 2017-03-23 15:31
 */
@RestController
@RequestMapping("/api")
@Api(tags="登录接口")
public class ApiLoginController {
    @Autowired
    private UserService userService;
    @Autowired
    private TokenService tokenService;


    @PostMapping("/user/login")
    @SysLog("用户登录")
    @ApiOperation("登录")
    public R login(@RequestBody LoginForm form){
        //表单校验
        ValidatorUtils.validateEntity(form);

        //用户登录
        Map<String, Object> map = userService.login(form);

        return R.ok(map);
    }


    @Login
    @SysLog("用户退出系统")
    @PostMapping("/user/logout")
    @ApiOperation("退出")
    public R logout(@ApiIgnore @RequestAttribute("userId") String userId){
        tokenService.expireToken(userId);
        return R.ok();
    }


    @Login
    @SysLog("查询用户信息")
    @PostMapping("/user/info")
    @ApiOperation("查询用户信息")
    public R queryUserInfo(@ApiIgnore @RequestAttribute("userId") String userId){

        //用户登录
        UserEntity userEntity = userService.selectById(userId);

        return R.ok().put("userinfo", userEntity);
    }

    @Login
    @PostMapping("/user/name/{userId}")
    @ApiOperation("查询用户姓名")
    public R queryUserName(@PathVariable String userId){

        //用户登录
        UserEntity userEntity = userService.selectById(userId);

        if(null == userEntity) {
            return R.ok().put("userName", "匿名用户");
        }else{

            return R.ok().put("userName", userEntity.getUserName());
        }

    }


    @Login
    @SysLog("更新用户信息")
    @PostMapping("/user/update")
    @ApiOperation("更新用户信息")
    public R updateUserInfo(@RequestAttribute("userId") String userId, @RequestBody UserUpdateForm form){

        UserEntity user = new UserEntity();
        user.setUserName(form.getUserName());
        user.setMobile(form.getMobile());
        user.setUserId(userId);
        userService.updateById(user);

        return R.ok();

    }

}

class UserUpdateForm {
    private String userName;
    private String mobile;

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getMobile() {
        return mobile;
    }

    public void setMobile(String mobile) {
        this.mobile = mobile;
    }
}
